import logging
import time

from appium.webdriver.common.appiumby import AppiumBy
from appium.webdriver.common.mobileby import MobileBy
from appium.webdriver.webdriver import WebDriver
from selenium.common.exceptions import NoSuchElementException


class BasePage():
    """Page 基类"""
    def __init__(self,driver:WebDriver):
        self.driver = driver

    def back(self,num=1):
        for i in range(num):
            logging.info("后退操作-->")
            self.driver.back()
            time.sleep(1)

    def find(self,by,locator):
        logging.info(f"查找元素-->：定位符：{by}, 定位表达式{locator}")
        return self.driver.find_element(by,locator)

    def finds(self,by,locator):
        logging.info(f"查找元素集-->：定位符：{by}, 定位表达式{locator}")
        return self.driver.find_elements(by,locator)

    def find_and_click(self,by,locator):
        self.find(by,locator).click()
        logging.info("点击操作<--")

    def find_and_send(self,by,locator,text):
        self.find(by,locator).send_keys(text)
        logging.info(f"输入操作<--输入内容为：{text}")

    def swipe_find_text(self, text, num=5):
        """
        滑动num次，进行查找text
        """
        for i in range(num):
            try:
                element = self.find(MobileBy.XPATH, f"//*[@text='{text}']")
                return element
            except NoSuchElementException:
                logging.info("查找不到元素<--")
                # 滑动操作
                # 获取屏幕的尺寸 'width', 'height'
                size = self.driver.get_window_size()
                width = size.get("width")
                height = size.get("height")
                # 水平方向：屏幕中间，垂直方向，从屏幕的4/5 位置滑到1/5
                start_x = width / 2
                start_y = height * 4 / 5
                end_x = start_x
                end_y = height * 1 / 5
                self.driver.swipe(start_x, start_y, end_x, end_y, duration=2000)
                logging.info("上滑操作<--")
        else:
            raise NoSuchElementException(f"找了{num}次，未找到text={text}")

    def swipe_find_text_to_click(self, text, num=5):
        """ 滑动查找text并点击"""
        self.swipe_find_text(text,num).click()
        logging.info("点击操作<--")